﻿using AutoMapper;
using HamcoWcs.Contract;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.Contract.ContractPcon.IPconDbMsgParsers;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.DeviceMsgQueues;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.Devices;
using HamcoWcs.Service.Common;

namespace HamcoWcs.Service.Pcon.PconPlcDbMsgParsers
{
    [AutoInject(typeof(IBasePconParser), InjectType.Scope)]
    public abstract class PconMsgParseBase : ScopeServiceBase, IBasePconParser
    {
        protected readonly IMesCommunicateService _mesCommunicateService;

        protected PconMsgParseBase(IMesCommunicateService mesCommunicateService, WcsDbContext wcsDbContext, IMapper mapper) : base(wcsDbContext, mapper)
        {
            _mesCommunicateService = mesCommunicateService;
        }

        public abstract EnumPconPlcRequest RequestType { get; }

        public abstract void Deal(PconDto pconDto, PconPlc pconPlc);

        /// <summary>
        /// 拒绝切换栈板类型
        /// </summary>
        /// <param name="pconDto">CV</param>
        protected virtual void RejectChangePalletType(PconDto pconDto)
        {
            var pconSendMsg = new PconSendMsg()
            {
                ErrorCode = 9,
                Request = (ushort)EnumPconSendMsg.ChangePalletFailure,
                PconName = (ushort)pconDto.PconName
            };

            InsertMsgQueue(new DeviceMsgQueueDto(pconDto, pconSendMsg));
        }

        /// <summary>
        /// 拒绝切换出入库模式
        /// </summary>
        /// <param name="pconDto"></param>
        protected virtual void RejectChangeMode(PconDto pconDto,ushort errorCode)
        {
            var pconSendMsg = PconSendMsg.CreateRejectChangeModeMsg(pconDto);
            pconSendMsg.ErrorCode = errorCode;
            InsertMsgQueue(new DeviceMsgQueueDto(pconDto, pconSendMsg));
        }

        /// <summary>
        /// 码头验证失败
        /// </summary>
        /// <param name="pconDto"></param>
        protected virtual void RejectValid(PconDto pconDto,ushort errorCode)
        {
            var pconSendMsg = new PconSendMsg()
            {
                ErrorCode = errorCode,
                PconName = (ushort)pconDto.PconName,
                Request = (ushort)EnumPconSendMsg.ValidateFailure
            };
            InsertMsgQueue(new DeviceMsgQueueDto(pconDto, pconSendMsg));
        }


        /// <summary>
        /// 插入消息队列
        /// </summary>
        /// <param name="queueDto"></param>
        protected void InsertMsgQueue(DeviceMsgQueueDto queueDto)
        {
            var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(queueDto);
            _wcsDbContext.DeviceMsgQueues.Add(deviceMsgQueue);
            _wcsDbContext.SaveChanges();
        }
    }
}
